import 'package:erp_widget/src/components/dialog/dialog.dart';
import 'package:erp_widget/src/components/toast/toast.dart';
import 'package:erp_widget/src/components/widget/condition.dart';
import 'package:erp_widget/src/theme/index.dart';
import 'package:erp_widget/src/utils/formatter/money.dart';
import 'package:erp_widget/src/utils/num.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 价格组件
class DxPrice extends StatelessWidget {
  /// 因为是row，主轴对齐方式
  final MainAxisAlignment alignment;

  /// 是否显示.00
  final bool showZeroDecimal;

  /// 前缀
  final String? prefix;

  final TextStyle? prefixStyle;

  final Widget? prefixWidget;

  /// 价格
  final num? value;

  /// 后缀，但是最好不要与编辑价格同时使用
  final String? suffix;

  final TextStyle? suffixStyle;

  final Widget? suffixWidget;

  /// 是否可以编辑价格
  final bool canEditPrice;

  /// 修改的历史价格，这个价格需要外层去控制，如果没有修改就不要传递
  final String? originPrice;

  /// 编辑价格回调
  final Function(num v)? editPriceCallback;

  // 价格颜色
  final Color color;

  // 价格大小
  final double size;

  // 货币符号
  final String currency;

  // 保留的小数点
  final int decimal;

  // 是否按照千分号形式显示
  final bool thousands;

  final SizedBox _sizedBoxShrink = const SizedBox.shrink();

  const DxPrice({
    Key? key,
    this.alignment = MainAxisAlignment.start,
    this.showZeroDecimal = true,
    this.prefix,
    this.prefixStyle,
    this.prefixWidget,
    this.currency = '¥',
    required this.value,
    this.suffix,
    this.suffixStyle,
    this.suffixWidget,
    this.originPrice,
    this.canEditPrice = false,
    this.editPriceCallback,
    this.size = DxStyle.priceFontSize,
    this.color = DxStyle.priceTextRedColor,
    this.decimal = 2,
    this.thousands = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String integer = value!.toInt().toString();
    RegExp reg = RegExp(r"(\d)((?:\d{3})+\b)");
    double fontSizeMin = (size / 1.5).toDouble();
    if (thousands) {
      while (reg.hasMatch(integer)) {
        integer = integer.replaceAllMapped(reg, (match) => "${match.group(1)},${match.group(2)}");
      }
    }
    String decimalString = value!.toStringAsFixed(decimal).split('.')[1];
    Widget $widget = Row(
      textBaseline: TextBaseline.ideographic,
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: alignment,
      crossAxisAlignment: CrossAxisAlignment.baseline,
      children: <Widget>[
        DxCondition.bool(
          prefixWidget != null || prefix != null,
          trueBuilder: () => Padding(
            padding: const EdgeInsets.only(right: 5),
            child: prefixWidget ??
                (prefix == null ? _sizedBoxShrink : Text(prefix!, style: prefixStyle ?? DxStyle.$999999$12)),
          ),
        ),
        Text(currency, style: TextStyle(fontSize: fontSizeMin, color: color)),
        Text(integer, style: TextStyle(fontSize: size, color: color, fontWeight: DxStyle.priceIntegerFontWeight)),
        DxCondition.bool(
          showZeroDecimal,
          trueBuilder: () => Text(".$decimalString", style: TextStyle(fontSize: fontSizeMin, color: color)),
        ),
        originPrice == null
            ? _sizedBoxShrink
            : Text(
                "/${DxNum.trim0(originPrice)}",
                style: const TextStyle(
                    textBaseline: TextBaseline.ideographic,
                    color: DxStyle.cardOriginPriceColor,
                    fontSize: DxStyle.cardOriginPriceFontSize,
                    decoration: TextDecoration.lineThrough),
              ),
        canEditPrice == false
            ? _sizedBoxShrink
            : const Padding(
                padding: EdgeInsets.only(left: 5),
                child: Icon(Icons.border_color_outlined, size: DxStyle.cardOriginPriceFontSize, color: DxStyle.$999999),
              ),
        DxCondition.bool(
          suffixWidget != null || suffix != null,
          trueBuilder: () => Padding(
            padding: const EdgeInsets.only(left: 5),
            child: suffixWidget ??
                (suffix == null ? _sizedBoxShrink : Text(suffix!, style: suffixStyle ?? DxStyle.$999999$12)),
          ),
        ),
      ],
    );

    if (canEditPrice == false) return $widget;
    return Builder(builder: (context) {
      return GestureDetector(
        onTap: () {
          TextEditingController controller = TextEditingController(text: '');
          DxDialog.textInput(
            context,
            title: '请输入商品价格',
            subTitle: '原价${originPrice ?? value}',
            placeholder: '请输入修改后的价格',
            keyboardType: TextInputType.numberWithOptions(decimal: true),
            inputFormatters: [DxMoneyLimitFormatter(2), FilteringTextInputFormatter.allow(RegExp('[0-9.,]+'))],
            controller: controller,
            beforeClose: (DxDialogAction action) async {
              if (action == DxDialogAction.confirm && controller.text == '') {
                DxToast.show('请输入修改后的价格');
                return false;
              }
              return true;
            },
            onConfirm: () {
              editPriceCallback?.call(num.parse(controller.text));
              controller.dispose();
            },
          );
        },
        child: $widget,
      );
    });
  }
}
